import rp from 'request-promise'
import {Loading, Message} from 'element-ui'
import router from "../router/index"
import {baseUrl} from "../config/env";


export default async (url = '', data = {}, type = 'GET') => {

    let loadingInstance = Loading.service({
        lock: true,
        fullscreen: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    if (localStorage.getItem("token")) {
        data.token = localStorage.getItem("token")
    } else {
        data.token = ""
    }

    type = type.toUpperCase();
    url = baseUrl + url;
    if (type == 'GET') {

        var options = {
            uri: url,
            qs: data,
            headers: {
                'User-Agent': 'Yasenagat'
            },
            json: true // Automatically parses the JSON string in the response
        };

        return rp(options).promise()
            .bind(this)
            .then(function (response) {
                if (process.env.NODE_ENV != 'development') {
                    console.log("get res :")
                    console.log(response)
                }
                if (response) {
                    if (response.result == 0) {
                        return response
                    } else if (response.result == -10) {
                        Message.error({message: '登录超时，请重新登录'})
                        localStorage.clear()
                        router.push("/")
                        return null
                    }
                } else {
                    return response
                }
                return response
            })
            .catch(function (err) {
                // API call failed...
                console.log(err)
                return {result: '-9999', message: err.statusCode}
            }).finally(function () {
                // console.log(loadingInstance)
                setTimeout(() => {
                    loadingInstance.close();
                }, 200);
                // This is called after the request finishes either successful or not successful.
            });
    } else {
        var options = {
            method: 'POST',
            uri: url,
            form: data,
            json: true,
            headers: {
                /* 'content-type': 'application/x-www-form-urlencoded' */ // Is set automatically
            },
            // resolveWithFullResponse: true
        };

        return rp(options)
            .promise()
            .bind(this)
            .then(function (response) {
                // POST succeeded...
                if (process.env.NODE_ENV != 'development') {
                    console.log("post res : ")
                    console.log(response)
                }
                if (response) {
                    if (response.result == 0) {
                        return response
                    } else if (response.result == -10) {
                        Message.error({message: '登录超时，请重新登录'})
                        localStorage.clear()
                        router.push("/")
                        return null
                    }
                } else {
                    return response
                }
                return response
            }).catch(function (err) {
                // POST failed...
                console.log(err)
                return {result: '-9999', message: err.statusCode}
            }).finally(function () {
                // console.log(loadingInstance);
                setTimeout(() => {
                    loadingInstance.close();
                }, 200);
                // This is called after the request finishes either successful or not successful.
            });
        ;
    }
}
